#!/usr/local/bin/python
# -*- coding: utf-8 -*-

import datetime
from flask import Flask, url_for, request, session, jsonify, render_template, redirect
from flaskext.sqlalchemy import SQLAlchemy
from json import dumps

from bompy import app
from utils import table, get2parameters, options, designoptions, unitoptions, formtable, login_required, textinput
from model import Reason, Storage, Design, Stock,Movement

db = SQLAlchemy(app)


@app.route('/domovement')
@login_required
@get2parameters
def domovement():
    r=[]
    for i in Reason.query.all():
        r.append((i.ID_Reason,i.Description))
    s=[]
    for i in Storage.query.all():
        s.append((i.ID_Storage,i.Description))
    print r
    print s
    form = (
    ("Product",designoptions("ID",types=[1,2,3,4,5])),
    ("Quantity",textinput("QU")),
    ("From",options(s,"FROM")),
    ("To",options(s,"TO")),
    ("Reason",options(r,"RE")),
    ("Note",textinput("NO"))
    )
    f= formtable(form, action="_movement_db")
    return render_template("domovement.html",f=f)

@app.route('/_movement_db')
@get2parameters
def movement_db(ID, QU, FROM, TO, RE, NO):
    if not QU.isdigit() or int(QU) <0:
        return "error, bad Quantity"
    qu = int(QU)
    des = Design.getCurrent(ID)
    rea = Reason.query.get(RE)
    end = rea.Type_End
    ini = rea.Type_Ini
    fro = Storage.query.filter_by(ID_Storage=FROM).first()
    to = Storage.query.filter_by(ID_Storage=TO).first()
    
    if not (fro.Type == ini and to.Type == end):
        return "bad reason"
    
    if des.ID_Design_Type == 1:
        designStock=0
        for i in Stock.query.filter_by(ID_Design=ID, End_Date=None, ID_Storage=FROM):
                designStock+=1
        
        if int(designStock)<qu:
            s="""not enough stock:<br />
            needed: """+str(qu)+"""<br />
            has: """+ str(designStock)
            return s
            
        
        moved=0
        for i in Stock.query.filter_by(ID_Design=ID, End_Date=None, ID_Storage=FROM):
                if moved < qu:
                    i.ID_Storage = to.ID_Storage #TODO hacer que al updatear se mantenga la informacion anterior
                    i.Update_Date = datetime.datetime.now()
                    db.session.merge(i)

                    db.session.commit()
                    moved+=1
    else:
        sto = Stock.query.filter_by(ID_Design=ID, ID_Storage=FROM).first()
        if sto.Quantity < qu:
            return "not enough stock"
        if sto.Quantity == qu:
            sto.Storage = to #TODO add editing history
        if sto.Quantity > qu:
            sto.Quantity = sto.Quantity - qu
            db.update(sto)
            
            newsto = Stock()
            newsto.ID_Design = sto.ID_Design
            newsto.ID_Storage = to.ID_Storage
            newsto.Start_Date = datetime.datetime.now()
            newsto.Quantity = qu
            newsto.Bar_Code = 0
            newsto.ID_State = 1
            newsto.User_Create = 1
            newsto.Start_Date = datetime.datetime.now()
            db.session.add(newsto)
            
            db.session.commit()

    mov = Movement()
    mov.ID_Reason = rea.ID_Reason
    mov.ID_Design = des.ID_Design
    mov.Source_Location = fro.ID_Storage
    mov.Destination_Location = to.ID_Storage
    mov.Quantity=qu
    mov.ID_Unit=1
    mov.Note=NO
    mov.Start_Date = datetime.datetime.now()
    mov.User_Create = 1 #session["Usercode"]
    mov.Lot=0
    db.session.add(mov)
    db.session.commit()
    return redirect(url_for('viewmovements'))

    
@app.route('/viewmovements')
@login_required
@get2parameters
def viewmovements():
    t=table(["ID Design","Description","Quantity","Unit","Reason","Source","Destination","Note","Date"])
    return render_template("viewmovements.html",t=t)
    
    
@app.route('/_movements_search')
@login_required
def movements_search():
    d={"aaData":[]}
    q = Movement.query.all()
    for i in q:
        d["aaData"].append(i.table())
    return dumps(d)    
    
    
    
